/**
 * 
 */
package com.yidin.logic;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

import com.yidin.util.AspLog;

import android.content.Context;

/**
 * @author cola
 * 
 */
public class httpCon {
	private static final String TAG = "httpCon";
	private static httpCon mSingleInstance = null;
	private int mMyPid;
	private Context ctx;
	private DefaultHttpClient mHttpClient;

	/**
	 * 获取URL中的文件名
	 * 
	 * @return 文件名
	 */
	static public String getUrlFileName(String url) {
		if (url.length() > 2)
			url = url.substring(url.lastIndexOf("/") + 1, url.length());
		return url;
	}

	static public httpCon getDefault(Context context) {
		int mypid = android.os.Process.myPid();
		if (mSingleInstance == null || mypid != mSingleInstance.mMyPid) {
			mSingleInstance = new httpCon(context);
		}
		return mSingleInstance;
	}

	private httpCon(Context context) {
		ctx = context;
		mMyPid = android.os.Process.myPid();

		// if (FileAdapter.isSdCardExist()) {
		// localLogPath = FileAdapter.getSdCardRootDir();
		// } else {
		// localLogPath = FileAdapter.getFilesDir(ctx);
		// }
		// localLogPath += "HttpRespLog.xml";

		HttpParams params = new BasicHttpParams();
		// 设置一些基本参数
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
		// HttpProtocolParams.setUseExpectContinue(params, true);
		ConnManagerParams.setMaxTotalConnections(params, 60);
		ConnPerRouteBean connPerRoute = new ConnPerRouteBean(30);
		ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);
		// params.setParameter(ClientPNames.CONNECTION_MANAGER_FACTORY, new
		// MMConnectionManagerFactory());

		// 设置我们的HttpClient支持HTTP和HTTPS两种模式
		SchemeRegistry schReg = new SchemeRegistry();
		schReg.register(new Scheme("http", PlainSocketFactory
				.getSocketFactory(), 80));
		// schReg.register(new Scheme("https",
		// SSLSocketFactory.getSocketFactory(), 443));

		// 使用线程安全的连接管理来创建HttpClient
		ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
				params, schReg);
		mHttpClient = new DefaultHttpClient(conMgr, params);
		// mHttpClient.setReuseStrategy(new NoConnectionReuseStrategy());//
		// cola:实测中，重用策略会导致一些网络异常错误
	}

	static public void shutdown() {
		if (mSingleInstance != null) {
			mSingleInstance.mHttpClient.getConnectionManager().shutdown();
			mSingleInstance = null;
		}
	}

	protected String appendString(InputStream inputStream) {
		StringBuffer sb = new StringBuffer();
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				inputStream));
		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (Exception e) {

				}
			}
		}

		return sb.toString();
	}

	public String doGet(String url) {
		HttpGet httpGet = new HttpGet(url);

		HttpResponse httpReponse = null;
		String sb = "";
		try {
			httpReponse = mHttpClient.execute(httpGet);
			sb = appendString(httpReponse.getEntity().getContent());
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		AspLog.d("httpCon", "runGet:" + sb);
		return sb;
	}
	
	/**
	 * 将字符串转成 http 编码
	 * @param url
	 * @return
	 */
	public String getEncordUrl(String url){
		try {
			return URLEncoder.encode(url,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}
}
